package com.v1.video.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.iss.view.common.ToastAlone;
import com.v1.video.R;
import com.v1.video.domain.ChooseAlbumPageInfo;
import com.v1.video.domain.ChooseAlbumPageObj;
import com.v1.video.domain.ChooseAlbumPageOffical;
import com.v1.video.domain.ChooseAlbumPageUser;
import com.v1.video.domain.LoginInfo;
import com.v1.video.domain.SpecialInfo;
import com.v1.video.engine.NetEngine;
import com.v1.video.util.Utils;

public class SelectAlbumActivity extends BaseActivity implements OnClickListener {
	
	private EditText mAblumTxt;
	private ListView mAblumLv;
	private String[] mAblumTag;
	  
	private List<ArrayList<SpecialInfo>> mAblums = new ArrayList<ArrayList<SpecialInfo>>();
//	private HashMap<String,ArrayList<SpeciaInfo>> mAblums;
	private MyListAdapter mAdapter;
	
	private int colnum=4;
	private int rowHeight=45;
	private int padding=20;
	
	TextView mCancel;
	TextView mConfirm;
	
	private String mCurSelTag="";
	private long mCurSelId=-1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.select_album_lay);
	}

	@Override
	protected void initView() {
		
		findViewById(R.id.iv_back).setVisibility(View.GONE);
		((TextView)findViewById(R.id.tv_caption)).setText(R.string.save_share_add_album);
		mCancel=(TextView)findViewById(R.id.tv_cancel);
		mCancel.setVisibility(View.VISIBLE);
		mConfirm=(TextView)findViewById(R.id.tv_confirm);
		mConfirm.setVisibility(View.VISIBLE);
		mConfirm.setText("确定");
		/*ImageView titleImg=(ImageView)findViewById(R.id.iv_titleImg);
		titleImg.setVisibility(View.VISIBLE);*/
		//titleImg.setBackgroundResource(R.drawable.quanzi_tag_ico);
		mAblumTxt=(EditText)findViewById(R.id.ablumTxt);
		mAblumLv=(ListView)findViewById(R.id.ablumLv);
	}

	@Override
	protected void initData() {
		 mAblumTag=new String[]{
					this.getResources().getString(R.string.myself_ablum),
					this.getResources().getString(R.string.hot_ablum)};
		
//		mAblums=new ArrayList<ArrayList<String>>();
//		ArrayList<String> item=new ArrayList<String>();
//		for(int i=0;i<20;i++){
//			item.add(mAblumTag[0]+i);
//		}
//		mAblums.add(item);
//		
//		item=new ArrayList<String>();
//		for(int i=0;i<18;i++){
//			item.add(mAblumTag[1]+i);
//		}
//		mAblums.add(item);
		
//		mAdapter=new MyListAdapter();
//		mAblumLv.setAdapter(mAdapter);
		
		new GetDataAsync().execute();
	}

	@Override
	protected void setListener() {
		mCancel.setOnClickListener(this);
		mConfirm.setOnClickListener(this);
	}
	
	@Override
	public void onClick(View arg0) {
		switch(arg0.getId()){
		case R.id.tv_cancel:
			back();
			break;
		case R.id.tv_confirm:
			mCurSelTag = mAblumTxt.getText().toString();
			Intent intent=new Intent();
			intent.putExtra("data", mCurSelTag);
			intent.putExtra("id", mCurSelId);
			setResult(RESULT_OK,intent);
			finish();
			break;
		}
		
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			back();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void back() {
		setResult(RESULT_CANCELED, new Intent());
		finish();
	}
	
	private class MyListAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mAblums.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return mAblums.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			PlaceHolder holder;
			if(convertView==null){
				convertView=LayoutInflater.from(SelectAlbumActivity.this).inflate(R.layout.select_album_lay_item, null);
				holder=new PlaceHolder();
				holder.groupHeaderTxt=(TextView)convertView.findViewById(R.id.groupHeaderTxt);
				holder.ablumGv=(GridView)convertView.findViewById(R.id.ablumGv);
				holder.ablumGv.setNumColumns(colnum);
				convertView.setTag(holder);
			}else{
				holder=(PlaceHolder)convertView.getTag();
			}
			
		    holder.groupHeaderTxt.setText(mAblumTag[position]);
			MyGridViewAdapter adapter=new MyGridViewAdapter(mAblums.get(position));
			int count=mAblums.get(position).size();
			int rownum=count%4==0?(count/4):(count/4+1);
			holder.ablumGv.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, Utils.dip2px(SelectAlbumActivity.this, rownum*rowHeight+padding)));
			
			holder.ablumGv.setAdapter(adapter);
			
			return convertView;
		}
		
		private class PlaceHolder
		{
			private TextView groupHeaderTxt;
			private GridView ablumGv;
		}
		
	}
	
	private class MyGridViewAdapter extends BaseAdapter{
		
		private List<SpecialInfo> lists;
		
		public MyGridViewAdapter(List<SpecialInfo> lists){
			this.lists=lists;
		}
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return lists.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return lists.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			PlaceHolder holder;
			if(convertView==null){
				convertView=LayoutInflater.from(SelectAlbumActivity.this).inflate(R.layout.select_album_lay_item_item, null);
				holder=new PlaceHolder();
				holder.itemTxt=(TextView)convertView.findViewById(R.id.textView1);
				convertView.setTag(holder);
			}else{
				holder=(PlaceHolder)convertView.getTag();
			}
			String name = lists.get(position).getAname();
			if(name == null || name.equals("null") || name.equals("")){
				name = lists.get(position).getOaName();
			}
			holder.itemTxt.setText(name);
			if (!TextUtils.isEmpty(lists.get(position).getId() + "")) {
				holder.itemTxt.setTag(lists.get(position).getId());
			}
			holder.itemTxt.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View arg0) {
					TextView tx=(TextView)arg0;
					mCurSelTag=tx.getText().toString();
					if (arg0.getTag() != null) {
						mCurSelId = Long.parseLong(arg0.getTag() + "");
					}
					mAblumTxt.setText(mCurSelTag);
					mAdapter.notifyDataSetChanged();
				}});
			
			if(mCurSelTag.equals(name)){
				holder.itemTxt.setBackgroundResource(R.drawable.select_tag_selected);
				holder.itemTxt.setTextColor(SelectAlbumActivity.this.getResources().getColor(R.color.color_blue));
			}else{
				holder.itemTxt.setBackgroundResource(R.drawable.select_tag_selector);
				Resources resource = (Resources) getBaseContext().getResources();  
				ColorStateList csl = (ColorStateList) resource.getColorStateList(R.color.select_tag_color);  
				if (csl != null) {  
					holder.itemTxt.setTextColor(csl); 
				}  
			}
			
			return convertView;
		}
		
		private class PlaceHolder
		{
			private TextView itemTxt;
		}
		
	}
	
	/**
     * 获取专辑
     */
    private class GetDataAsync extends AsyncTask<Void, Void, Boolean> {
        
        private String errorMsg = "";
        
        private ProgressDialog pd;
        ChooseAlbumPageInfo albumPageInfo;
        public GetDataAsync() {                        
           
        }
        
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pd = Utils.getProgressDialog(SelectAlbumActivity.this,getResources().getString(R.string.get_data), this);
            pd.show();
        }
        
        @Override
        protected Boolean doInBackground(Void... params) {
            try {
                NetEngine engine = new NetEngine();
                albumPageInfo = engine.getAlbum(LoginInfo.getInstance().getUserId());
            } catch (Exception e) {
                e.printStackTrace();
                errorMsg = e.getMessage();
            }
            return false;
            
        }
        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            if(pd != null && pd.isShowing()){
                pd.cancel();
            }            
            if (errorMsg.equals("")) {
                if(albumPageInfo != null){
                	if(albumPageInfo.getCode() == 0){
                		ChooseAlbumPageObj albumPageObj = albumPageInfo.getObj();
                		ChooseAlbumPageOffical albumPamgeOffical = null;
                		ChooseAlbumPageUser albumPamgeUser = null;                		
                		if(albumPageObj != null){
                			albumPamgeOffical = albumPageObj.getOfficialAlbum();
                			albumPamgeUser = albumPageObj.getUserAlbum();
                			
                			if(albumPamgeUser != null){
                				if(albumPamgeUser.getRows() != null){
                					mAblums.add(albumPamgeUser.getRows());
                				}
                			}
                			if(albumPamgeOffical != null){
                				if(albumPamgeOffical.getRows() != null){
                					mAblums.add(albumPamgeOffical.getRows());
                				}
                			}
                			mAdapter=new MyListAdapter();
                			mAblumLv.setAdapter(mAdapter);
                		}
                	}else{
                		ToastAlone.showToast(SelectAlbumActivity.this, albumPageInfo.getMsg(), 1);
                	}
                }else{
                	ToastAlone.showToast(SelectAlbumActivity.this, errorMsg, 1);
                }
            } else {
                ToastAlone.showToast(SelectAlbumActivity.this, errorMsg, 1);
            }
        }
    }
}
